<template>
  <div class="login">
    <section class="login-box animate__animated animate__zoomIn">
      <!-- 左侧 -->
      <div class="login-left">
        <img class="login-img" src="@/assets/svgs/login-img.svg" />
      </div>
      <!-- 右侧 -->
      <div class="login-right">
        <a-form
          ref="FormRef"
          :model="form"
          :style="{ width: '84%' }"
          :label-col-style="{ display: 'none' }"
          :wrapper-col-style="{ flex: 1 }"
        >
          <h3 class="login-form-title">
            <!-- <img class="logo" src="@/assets/images/logo.gif" /> -->
            <span>恒蓝云后台管理系统</span>
          </h3>
          <a-form-item field="username" :rules="[{ required: true, message: '请输入账号' }]">
            <a-input v-model="form.username" placeholder="账号 admin/user" size="medium" allow-clear>
              <template #prefix><icon-user :stroke-width="1" :style="{ fontSize: '20px' }" /></template>
            </a-input>
          </a-form-item>
          <a-form-item field="password" :rules="[{ required: true, message: '请输入密码' }]">
            <a-input-password v-model="form.password" placeholder="密码" size="medium" @press-enter="login" allow-clear>
              <template #prefix><icon-lock :stroke-width="1" :style="{ fontSize: '20px' }" /></template>
            </a-input-password>
          </a-form-item>
          <a-form-item>
            <a-row justify="space-between" align="center" style="width: 100%">
              <a-checkbox v-model="checked">记住密码</a-checkbox>
            </a-row>
          </a-form-item>
          <a-form-item>
            <a-space direction="vertical" fill style="width: 100%">
              <a-button type="primary" size="large" long :loading="loading" @click="login">登录</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </section>

    <!-- <GiThemeBtn class="theme-btn"></GiThemeBtn> -->

    <LoginBg></LoginBg>
  </div>
</template>

<script setup lang="ts">
import { useUserStore, usePermissionStore } from '@/store'
// import router from '@/router'
import { useLoading } from '@/hooks'
import { Message, Notification, type FormInstance } from '@arco-design/web-vue'
import LoginBg from './components/LoginBg/index.vue'
import * as Regexp from '@/utils/regexp'
import { onMounted } from 'vue'
import { getNowDate, getRemainderTime } from '@/utils/myUtils'

// import { usePermissionStore } from '@/store'
// const permissionStore = usePermissionStore()

// 初始化阶段
onMounted(() => {
  // 如果本地有记住密码时存储的密码，则取出使用
  const pwa = localStorage.getItem('password')
  // //console.log(pas)
  if (pwa != null && pwa != '' && pwa != undefined) {
    form.password = pwa
    checked.value = true
  }
  let tokenSetTime = localStorage.getItem('tokenSetTime')
  console.log(tokenSetTime)
  if (tokenSetTime == null) {
    tokenSetTime = '2022-12-12 00:00:00'
  }
  // console.log(localStorage.getItem('token'))

  // console.log(localStorage.getItem('token') == null)

  if (
    getRemainderTime(tokenSetTime)[3] >= 2 &&
    getRemainderTime(tokenSetTime)[2] == 0 &&
    getRemainderTime(tokenSetTime)[1] == 0 &&
    getRemainderTime(tokenSetTime)[0] == 0 &&
    localStorage.getItem('token') == ''
  ) {
    Message.error('token已过期，请重新登录!')
  } else if (localStorage.getItem('token') == null) {
  }
})

defineOptions({ name: 'Login' })
const router = useRouter()
const userStore = useUserStore()
const persStore = usePermissionStore()

const form = reactive({
  username: 'lohand',
  password: ''
})

// 记住密码
const checked = ref(false)
// 登录加载
const { loading, setLoading } = useLoading()
const errorMessage = ref('')

const FormRef = ref<FormInstance>()

// 点击登录
const login = async () => {
  // 判断记住密码是否选中
  // 如果选择，将本次的密码存储到本地
  if (checked.value) {
    localStorage.setItem('password', form.password)
  } else {
    localStorage.removeItem('password')
  }
  try {
    const flag = await FormRef.value?.validate()
    if (flag) return
    setLoading(true)
    await userStore
      .login(form.username, form.password)
      .then(async (res) => {
        // 遍历向路由表添加数据
        const accessRoutes = await persStore.generateRoutes()
        console.log(accessRoutes, 'accessRoutes')

        accessRoutes.forEach((route) => {
          // if (!isHttp(route.path)) {
          router.addRoute(route) // 动态添加可访问路由表
          // }
        })
        Message.success('登录成功')
        Notification.success({
          title: '欢迎回来',
          content: `${userStore.getTimeState()},${userStore.userName}!`,
          closable: true,
          style: { fontSize: '20px', color: 'red' }
        })
      })
      .catch((err) => {
        // if (err.data) {
        //   Message.error(err.data)
        // }
        Message.error('登录失败,请联系管理员!')
        console.log(err)
      })
    setLoading(false)

    userStore.getLocalWeather()

    router.push('/home')
    // persStore.generateRoutes()
  } catch (error) {
    //console.log(error)
    errorMessage.value = (error as Error).message
  } finally {
    setLoading(false)
  }
  //console.log('跳转');
}
</script>

<style lang="scss" scoped>
.register-btn,
.register-btn:hover {
  color: var(--color-text-2);
}

.login-form-title {
  color: var(--color-text-1);
  font-weight: 500;
  font-size: 20px;
  line-height: 32px;
  margin-bottom: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  .logo {
    width: 32px;
    height: 32px;
    margin-right: 6px;
  }
}

.theme-btn {
  position: fixed;
  top: 20px;
  left: 30px;
  z-index: 9999;
}

.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--color-bg-5);
  &-box {
    width: 720px;
    height: 380px;
    display: flex;
    z-index: 999;
    box-shadow: 0 2px 4px 2px rgba(0, 0, 0, 0.08);
  }
}

.login-left {
  flex: 1;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  background: linear-gradient(60deg, rgb(var(--primary-6)), rgb(var(--primary-3)));
  .login-img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    transition: all 0.3s;
    object-fit: cover;
  }
}

.login-right {
  width: 270px;
  height: 100%;
  background: var(--color-bg-1);
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 30px;
  box-sizing: border-box;
}
</style>
